package com.gome.TestUtil.sha1;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * @author tx_hemaojie
 * 
 * @version 1.0
 * 
 * @created 2013-6-28 下午4:10:32
 */
public class SHA1Encrypt {

	public String Encrypt(String strSrc, String encName) {

		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	public static void main(String[] args) {
		SHA1Encrypt te = new SHA1Encrypt();
		String strSrc = "123456<$Head$><$Version$>1.0.0.0</$Version$><$TestFlag$>Y</$TestFlag$></$Head$><$Body$><$MchMchNbr$>020012</$MchMchNbr$><$MchBllNbr$>2100045685</$MchBllNbr$><$MchBllDat$>20130627</$MchBllDat$><$MchBllTim$>102623</$MchBllTim$><$TrxTrxCcy$>156</$TrxTrxCcy$><$TrxBllAmt$>1000.00</$TrxBllAmt$><$TrxPedCnt$>6</$TrxPedCnt$><$UIHidePed$>gome</$UIHidePed$><$MchUsrIdn$>gome</$MchUsrIdn$><$MchNtfUrl$>http://10.57.40.16:8080/payment/index.jsp</$MchNtfUrl$><$MchNtfPam$>gome</$MchNtfPam$><$TrxGdsGrp$>gome</$TrxGdsGrp$><$TrxGdsNam$>gome</$TrxGdsNam$><$TrxPstAdr$>gome</$TrxPstAdr$><$TrxPstTel$>gome</$TrxPstTel$></$Body$>";
		System.out.println("Source String:" + strSrc);
		System.out.println("Encrypted String:");
		System.out.println("Use Def:" + te.Encrypt(strSrc, null));
		System.out.println("Use MD5:" + te.Encrypt(strSrc, "MD5"));
		System.out.println("Use SHA:" + te.Encrypt(strSrc, "SHA-1"));
		System.out.println("Use SHA-256:" + te.Encrypt(strSrc, "SHA-256"));
	}

}
